import serviceList from "./service";

const generate = require('nanoid/generate');
import request from '@/utils/request';

export default {
  /**
   * 根据配置获取数据
   * @param setting 配置
   * @param params 参数
   * @param callback 回调
   */
  loadData(setting, params, callback) {
    let api = null;
    const queryParams = this.buildQueryParams(setting, params);

    if (setting.serviceType === 'defined') {
      const service = serviceList.find(item => item.code === setting.code);
      api = service.api;
    } else {
      api = this.buildCustomApi(setting, queryParams);
    }

    let filterMethodName = this.addFilterMethod(setting);

    //调用预定义接口
    this.queryData(api, queryParams, filterMethodName, callback);
  },

  buildCustomApi(setting, params) {
    let url = setting.url;
    if (url.indexOf('{') !== -1) {
      Object.keys(params).forEach(key => {
        url = url.replace('{' + key + '}', params[key]);
      });
    }
    return function () {
      return request({
        url: url,
        method: 'get',
        params: params
      })
    }
  },

  //构建查询参数
  buildQueryParams(setting, params) {
    const queryParams = {};
    if (setting.paramList && setting.paramList.length) {
      setting.paramList.forEach(p => {
        let val;
        if (p.type === '&' && p.value && params[p.value]) {
          val = params[p.value];
        } else {
          val = p.value;
        }
        queryParams[p.code] = val;
      })
    }
    return queryParams;
  },

  //添加过滤数据脚本
  addFilterMethod(setting) {
    let name = null;
    if (setting.useFilter && setting.resultFilter) { //过滤数据
      name = 'filter_' + generate('1234567890abcdef', 10);
      const resultFilter = setting.resultFilter.replace('_filter', name);
      const script = document.createElement("script");
      script.append(document.createTextNode(resultFilter));
      document.getElementsByTagName("head")[0].appendChild(script);
    }
    return name;
  },

  //调用接口
  queryData(api, queryParams, filterMethodName, callback) {
    queryParams.validDeviceStatus = true;
    api(queryParams).then(res => {
      let data = res.data || res.rows;
      if (filterMethodName) {
        //调用数据过滤方法
        data = window[filterMethodName](data);
      }
      if (res.rows) { //列表数据
        res.rows = data;
        callback(res);
      } else {
        callback(data);
      }

    }).catch(err => {
      console.error(err);
      callback({});
    });
  }

}
